#include<vector>
#include<iostream>
using std::vector;


class Solution {
public:
    void nextPermutation(vector<int>& nums) {
        int n = nums.size() - 1;
        for (; n > 0; n--) {
            if (nums[n] > nums[n-1]) break;
        }
        //std::cout << "idx: " << n << nums[n] << "\n";
        // 检查n是否非0
        if (n == 0) {
            this->reverse(nums, 0, nums.size()-1);
        }
        else {
            // n>0, 此时从n开始生成一个最小排列
            n -= 1;
            int left = n+1, right = nums.size(), idx = -1;
            while (left < right) {
                auto mid = (left + right) / 2;
                //std::cout << left << ", " << mid << ", " << right << "\n";
                if (nums[mid] > nums[n]) {
                    if ((mid < nums.size() - 1 && nums[mid+1] <= nums[n]) || (mid >= nums.size()-1)) {
                        idx = mid;
                        break;
                    } 
                    else {
                        left = mid;
                    }
                }
                else {
                    right = mid;
                }
            }
            if (idx == -1) std::cout << "error";
            this->swap(nums, n, idx);
            this->reverse(nums, n+1, nums.size()-1);

        }
    }

    void reverse(vector<int>& nums, int left, int right) {
        while (left < right) {
            this->swap(nums, left, right);
            left++;
            right--;
        }
    }

    void swap(vector<int>& nums, int i, int j) {
        auto temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
};


int main() {
    vector<int> input = {};
    int n;
    while (std::cin >> n) {
        input.push_back(n);
    }
    std::cout << "input: \n";

    for (auto k: input) std::cout << k << " ";
    std::cout << "\n";

    Solution().nextPermutation(input);
    std::cout << "next permutation: ";
    for (auto k: input) std::cout << k << " ";
    std::cout << "\n";

}